package com.tcoiss.datafactory.config;

import com.tcoiss.common.datasource.DataSourceVo;
import com.tcoiss.common.datasource.DynamicDataSource;
import com.tcoiss.datafactory.domain.DataSource;
import com.tcoiss.datafactory.service.IDataSourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ApplicationRunnerService implements ApplicationRunner {

    private final Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private IDataSourceService iDataSourceService;

    @Autowired
    private DynamicDataSource dynamicDataSource;

    @Override
    public void run(ApplicationArguments args) {
        log.info("开始执行数据源初始化。。。。。。。"+"执行参数："+args);
        try{
            this.initDatasource();
        }catch (Exception e){
            log.info("执行失败。。。。");
            e.printStackTrace();
        }

    }

    //项目启动完成后初始化所有数据源
    public void initDatasource() throws Exception {
        log.info("开始初始化数据源列表！。。。。。。。。。。。。。。");
        DataSource dataSource = new DataSource();
        dataSource.setDataLevel(1);
        List<DataSource> dataSourceList = iDataSourceService.queryList(dataSource);
        for(DataSource dataSource1: dataSourceList){
            DataSourceVo vo = new DataSourceVo();
            vo.setDbName(dataSource1.getDbName());
            vo.setDatabaseName(dataSource1.getDatabaseName());
            vo.setDatabaseType(dataSource1.getDatabaseType());
            vo.setConncetAttr(dataSource1.getConncetAttr());
            vo.setIpAddress(dataSource1.getIpAddress());
            vo.setIpPort(dataSource1.getIpPort());
            vo.setPassWord(dataSource1.getPassWord());
            vo.setUserName(dataSource1.getUserName());
            dynamicDataSource.createDataSourceWithCheck(vo);
        }
        log.info("初始化数据源列表完成！。。。。。。。。。。。。。。");
    }

}
